﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Microsoft.Extensions.Options;

using Xc.DataAccess.OneNetCore.Services;
using Microsoft.Extensions.DependencyInjection;
using Xc.Views.Booster.Views;
using Microsoft.Win32;
using Xc.Logics.AepCoap.Models;
using System.IO;
using Xc.Logics.AepCoap.Services;
using Xc.DataAccess.Core;
using Xc.DataAccess.Core.Services;
using System.Collections.ObjectModel;
using System.Drawing;

namespace Xc.Logics.OneNet.Views
{
    /// <summary>
    /// MasterView.xaml 的交互逻辑
    /// </summary>
    public partial class MasterView : UserControl
    {
        private readonly IOneNetUploadService aepCoapService;
        private readonly IOneNetService oneNetService;
        private readonly ICsvService csvService;
        private readonly IOptions<AppSetting> options;
        private readonly IServiceProvider serviceProvider;
        public MasterView(IOneNetService oneNetService, IOptions<AppSetting> options, IServiceProvider serviceProvider, ICsvService csvService, IOneNetUploadService aepCoapService)
        {
            InitializeComponent();
            oneNetService.Options = options.Value.OneNetSetting;
            this.oneNetService = oneNetService;
            this.options = options;
            this.serviceProvider = serviceProvider;
            this.csvService = csvService;
            this.aepCoapService = aepCoapService;
        }

        private async void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            await Reload(_pager.PageIndex, _pager.PageSize);

        }

        private async Task Reload(int pageIndex, int pageSize)
        {
            this.ViewModel.Devices.Clear();

            try
            {
                var respond = await oneNetService.GetDevices(new QueryDevicesRequest { Page = pageIndex, PageSize = pageSize });
                if (respond.IsSuccess)
                {
                    _pager.SetPageInfo(new DotNetUI.Controls.PageInfo { CurrentPageCount = respond.Data.Devices.Count(),PageIndex=pageIndex,TotalCount=respond.Data.Count });
                    this.Dispatcher.Invoke(() =>
                    {
                        this.ViewModel.Devices.AddRange(respond.Data.Devices);
                    });
                }
                else
                {
                    MessageBox.Show(respond.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "错误");
            }
        }

        private async void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
        {
            if (MessageBox.Show($"确定要删除设备{ViewModel.SelectItem.Title}吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                var res = await oneNetService.DeleteDevice(ViewModel.SelectItem.DeviceId);
                if (res.IsSuccess)
                {
                    MessageBox.Show("删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show($"删除失败,{res.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);

                }
            }
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (this.ViewModel.SelectItem != null)
            {
                e.CanExecute = true;
            }
        }

        private async void dxg_Loaded(object sender, RoutedEventArgs e)
        {
            // await  Reload();
        }

        private async void filecsv_ItemClick(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var files = Directory.EnumerateFiles(folderBrowserDialog.SelectedPath, "*.csv", SearchOption.AllDirectories);
                    filename.Content = folderBrowserDialog.SelectedPath;
                    if (Models.Count() > 0)
                    {
                        Models.Clear();
                    }
                    foreach (var item in files)
                    {
                        await InitDeviceList(item);
                    }
                    Models = Models.OrderByDescending(p => p.CreateTime).GroupBy(g => g.IMEI).Select(p => p.FirstOrDefault()).ToList();
                    dxg.ItemsSource = Models;
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("请检查文件是否已打开，若打开请关闭" + err.Message);
            }
        }

        private void BarButtonItem_ItemClick(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<SettingView>().SetTitle("参数配置").SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetSizePercent(0.6).ShowDialog();
        }

        private void BarButtonItem_ItemClick_1(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<LogView>().SetTitle("操作说明").SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetWidthPercent(0.6).SetHeightPercent(0.6).ShowDialog();
        }

        private async void AddDevice_Click(object sender, RoutedEventArgs e)
        {
            await aepCoapService.UploadAsync(ck.IsChecked == true, Models, (result) =>
            {
                ToCsvFile(result.DateTime.ToString("yyyy/MM/dd HH:mm:ss"), result.DeviceNumber, result.IMEI, result.IMSI, result.Message);
            }, ViewModel.Devices);
            if (Models.Count() > 0)
            {

                //  await RefreshAsync();
            }
            else
            {
                MessageBox.Show("请先加载文件");
            }
        }
        public Result ToCsvFile(params string[] content)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "Data\\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var strfile = DateTime.Now.ToString("yyyyMMdd") + "_设备新增(修改)明细表.csv";
            var filename = path + strfile;
            return csvService.WriteToFile(filename, new List<string[]> { content }, "设备注册日期", "设备名称", "IMEI号", "IMSI号", "描述信息");
        }
        public List<AddDeviceModel> Models = new List<AddDeviceModel>();
        private async Task InitDeviceList(string filename)
        {

            var lists = await File.ReadAllLinesAsync(filename, Encoding.UTF8);
            if (lists.Count() > 0)
            {
                var buffers = lists.Skip(1).ToList();
                foreach (var item in buffers)
                {
                    AddDeviceModel model = new AddDeviceModel();
                    try
                    {
                        string[] vs = item.Split(',');
                        for (int i = 0; i < vs.Length; i++)
                        {
                            if (vs.Length == 3)
                            {
                                MessageBox.Show($"错误的设备，无法注册,第{i}行", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                continue;
                            }

                            if (vs.Length >= 4)
                            {
                                model.DeviceNumber = StrReplce(vs[1]);
                                model.ProductTime = StrReplce(vs[0]);
                                model.IMEI = StrReplce(vs[2]);

                                model.IMSI = StrReplce(vs[3]);
                                if (model.IMSI.Length != 15)
                                {
                                    model.IMSI = string.Empty;
                                }
                            }
                            else
                            {
                                model.IMSI = String.Empty;
                                continue;
                            }
                        }
                        if (!string.IsNullOrEmpty(model.IMEI) && model.Plantform == Plantform.移动)
                        {
                            Models.Add(model);
                        }
                    }
                    catch (Exception err)
                    {

                    }

                }

            }
        }
        private string StrReplce(string str)
        {
            string aa = str.Replace("'", "");
            return aa;
        }
        private async void dxg_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private async void _pager_GoToPage(object sender, DotNetUI.Models.PageInfoEventArgs e)
        {
            await Reload(e.PageIndex, e.PageSize);
        }
    }
}
